import Card from '@/components/Card';
import Description from '@/components/Description';
import HandleBtn from '@/components/HandleBar/btn';
import type { ActionType, ProColumns, ProFormInstance } from '@/components/Pro/';
import { ModalForm, ProFormDigit, ProFormText, ProTable } from '@/components/Pro/';
import { sysDictTypeControllerPageById as getPage } from '@/services/ess/sysDict';
import {
  sysDictItemControllerDeleteBatch as batchDelete,
  sysDictItemControllerEdit as edit,
  sysDictItemControllerExport as downloadFile,
  sysDictItemControllerSave as add,
  sysDictItemControllerSaveBatch as uploadFile,
} from '@/services/ess/sysDictItem';
import { downloadFetch } from '@/utils/downloadFile';
import type { UploadProps } from 'antd';
import { message, Modal, Space, Upload } from 'antd';
import React, { useRef, useState } from 'react';
import { getIntl, useIntl, useSearchParams } from 'umi';
const { confirm } = Modal;

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.SysDictItem) => {
  try {
    const res = await add({
      ...fields,
    });
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.addSuccessfully' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.addFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.SysDictItem) => {
  try {
    const res = await edit({
      ...fields,
    });
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.addSuccessfully' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.editFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.SysDictItem[]) => {
  if (!selectedRows) return true;
  try {
    const ids = selectedRows.map((row) => row.itemId);
    const res = await batchDelete(ids);
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.delSuccess' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.delFailedTips' }));
    return false;
  }
};

const TableList: React.FC<{
  id?: string;
}> = ({ id }) => {
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<API.SysDictItem>({});
  const [selectedRowsState, setSelectedRows] = useState<API.SysDictItem[]>([]);
  const [disabled, setDisabled] = useState(false);
  const intl = useIntl();

  const [searchParams] = useSearchParams();

  const deleteRow = (rows: API.SysDictItem[] = selectedRowsState) => {
    if (rows?.length < 1) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return;
    }

    if (disabled) return;
    setDisabled(true);

    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content: intl.formatMessage({ id: 'global.delTip' }),
      onOk: async () => {
        const res = await handleRemove(rows);
        if (res) {
          setSelectedRows([]);
          actionRef.current?.reloadAndRest?.();
        }
      },
      afterClose: () => {
        setDisabled(false);
      },
    });
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    customRequest: async (info) => {
      const form = new FormData();
      form.append('file', info.file);
      const res = await uploadFile({ typeId: searchParams.get('id') }, form, {
        ingoreErrorMsg: true,
      });
      if (res?.success) {
        message.success(`${info.file.name} ${intl.formatMessage({ id: 'global.iFileS' })}`);
        actionRef?.current?.reloadAndRest?.();
        return;
      }
      const msg = res?.message;
      message.error(
        `${info.file.name} ${intl.formatMessage({ id: 'global.iFileF' })} ${msg ? ',' + msg : ''}`,
      );
    },
  };

  const columns: ProColumns<API.SysDictItem>[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
      hideInSearch: true,
      dataIndex: 'pageIndex',
    },
    {
      title: intl.formatMessage({
        id: 'systemManagement.dataDictionary.dictionaryEntryNamenoTitle',
      }),
      dataIndex: 'itemName',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({
        id: 'systemManagement.dataDictionary.dataValue',
      }),
      dataIndex: 'itemValue',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'systemManagement.dataDictionary.dictionaryItemDescription',
      }),
      dataIndex: 'remark',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({
        id: 'systemManagement.dataDictionary.sort',
      }),
      dataIndex: 'sort',
      hideInSearch: true,
    },
    {
      dataIndex: 'keyword',
      fieldProps: () => {
        return {
          placeholder: intl.formatMessage({
            id: 'systemManagement.dataDictionary.pleaseEnterTheDictionaryName',
          }),
          style: { width: 350 },
        };
      },
      hideInTable: true,
    },
    {
      title: intl.formatMessage({
        id: 'systemManagement.generalProcedure.operation',
      }),
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <a
            key="edit"
            onClick={() => {
              handleModalOpen(true);
              setCurrentRow(record);
            }}
          >
            {intl.formatMessage({
              id: 'systemManagement.generalProcedure.edit',
            })}
          </a>
          <a key="delete" className="global-del-color" onClick={() => deleteRow([record])}>
            {intl.formatMessage({
              id: 'systemManagement.generalProcedure.delete',
            })}
          </a>
        </Space>
      ),
    },
  ];
  return (
    <div style={{ marginTop: 20 }}>
      <ProTable<API.SysDictItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'systemManagement.dataDictionary.dictionaryEntryName',
        })}
        actionRef={actionRef}
        formRef={formRef}
        rowKey="itemId"
        toolBarRender={() => [
          <HandleBtn
            handleType="add"
            key="add"
            onClick={() => {
              setCurrentRow({});
              handleModalOpen(true);
            }}
          >
            {intl.formatMessage({
              id: 'systemManagement.generalProcedure.new',
            })}
          </HandleBtn>,
          <Upload key="import" {...uploadProps}>
            <HandleBtn handleType="import">
              {' '}
              {intl.formatMessage({
                id: 'systemManagement.generalProcedure.import',
              })}
            </HandleBtn>
          </Upload>,
          <HandleBtn
            handleType="export"
            key="export"
            onClick={() =>
              downloadFetch(downloadFile, {
                ...formRef?.current?.getFieldsFormatValue(),
                isEmpty: false,
              })
            }
          >
            {intl.formatMessage({
              id: 'systemManagement.generalProcedure.export',
            })}
          </HandleBtn>,
          <HandleBtn onClick={() => deleteRow()} handleType="delete" key="delete">
            {intl.formatMessage({
              id: 'systemManagement.generalProcedure.batchDelete',
            })}
          </HandleBtn>,
        ]}
        request={async (params: API.sysDictTypeControllerPageByIdParams) => {
          const msg = await getPage({ ...params, typeId: id });
          return msg;
        }}
        search={{
          layoutType: 'Form',
          layout: 'inline',
          style: { padding: 30 },
          submitter: {
            searchConfig: {
              submitText: intl.formatMessage({
                id: 'systemManagement.generalProcedure.search',
              }),
            },
            resetButtonProps: false,
          },
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        initialValues={{ ...currentRow }}
        title={
          currentRow?.itemId
            ? intl.formatMessage({
                id: 'systemManagement.dataDictionary.editDictionaryEntries',
              })
            : intl.formatMessage({
                id: 'systemManagement.dataDictionary.addDictionaryEntry',
              })
        }
        width="730px"
        colProps={{ md: 12 }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          let success;
          value.typeId = id;
          if (currentRow?.typeId) {
            success = await handleEdit({ ...currentRow, ...value } as API.SysDictItem);
          } else {
            success = await handleAdd(value as API.SysDictItem);
          }
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          name="itemName"
          label={intl.formatMessage({
            id: 'systemManagement.dataDictionary.dictionaryEntryName',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.requiredFields.dictionaryItemName',
              }),
            },
          ]}
          fieldProps={{
            maxLength: 30,
          }}
        />
        <ProFormText
          name="itemValue"
          label={intl.formatMessage({
            id: 'systemManagement.dataDictionary.dataValue',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.dataValue' }),
            },
          ]}
          fieldProps={{
            maxLength: 30,
          }}
        />
        <ProFormText
          name="remark"
          label={intl.formatMessage({
            id: 'systemManagement.dataDictionary.dictionaryDescription',
          })}
          fieldProps={{
            maxLength: 140,
          }}
        />
        <ProFormDigit
          name="sort"
          label={intl.formatMessage({
            id: 'systemManagement.dataDictionary.sortingValues',
          })}
          min={1}
          max={9999}
          fieldProps={{
            placeholder: intl.formatMessage({
              id: 'systemManagement.requiredFields.numericalValue',
            }),
          }}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.sortValue' }),
            },
          ]}
        />
      </ModalForm>
    </div>
  );
};

const CollectingArchives: React.FC = () => {
  const [searchParams] = useSearchParams();
  const id = searchParams.get('id');
  const intl = useIntl();

  const items = [
    {
      key: '1',
      label: intl.formatMessage({ id: 'systemManagement.dataDictionary.creationtime' }),
      children: searchParams.get('createTime'),
    },
    {
      key: '2',
      label: intl.formatMessage({ id: 'systemManagement.dataDictionary.updateTime' }),
      children: searchParams.get('modifyTime'),
    },
    {
      key: '3',
      label: intl.formatMessage({ id: 'systemManagement.dataDictionary.dictionaryName' }),
      children: searchParams.get('typeName'),
    },
    {
      key: '4',
      label: intl.formatMessage({ id: 'systemManagement.dataDictionary.dictionaryCode' }),
      children: searchParams.get('typeCode'),
    },
    {
      key: '5',
      label: intl.formatMessage({ id: 'systemManagement.dataDictionary.dictionaryDescription' }),
      children: searchParams.get('remark'),
      span: 2,
    },
  ];
  return (
    <div>
      <Card
        title={intl.formatMessage({
          id: 'systemManagement.dataDictionary.dataDictionaryInformation',
        })}
      >
        <Description items={items} />
      </Card>
      <TableList id={id} />
    </div>
  );
};

export default CollectingArchives;
